package com.sgb.goods.utils.base;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;

import com.gyf.barlibrary.ImmersionBar;
import com.sgb.goods.BR;
import com.sgb.goods.R;
import com.sgb.goods.databinding.GoodsActivityBaseBinding;
import com.sgb.goods.databinding.GoodsViewLoadErrorBinding;
import com.sgb.goods.databinding.GoodsViewNoDataBinding;
import com.sgb.goods.databinding.GoodsViewNoNetworkBinding;
import com.sgb.goods.utils.StringUtils;
import com.sgb.goods.utils.base.viewmodel.BaseViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.LoadingDialog;

/**
 * Activity基类
 *
 * @param <DB>
 * @param <VM>
 * @author cyj
 */
public abstract class BaseActivity<DB extends ViewDataBinding, VM extends BaseViewModel>
        extends AppCompatActivity {

    public DB mDataBinding;
    protected VM mViewModel;
    private int variableId = 0;
    private GoodsActivityBaseBinding mBaseDataBinding;
    private GoodsViewLoadErrorBinding mViewLoadErrorBinding;
    private GoodsViewNoNetworkBinding mViewNoNetworkBinding;
    private GoodsViewNoDataBinding mViewNoDataBinding;
    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;

    @Override
    final protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initStatusBar();

        handleIntent(getIntent());

        mBaseDataBinding = DataBindingUtil.setContentView(this, R.layout.goods_activity_base);
        mDataBinding = DataBindingUtil.inflate(getLayoutInflater(), getLayoutResId(), mBaseDataBinding.flContentContainer, true);
        initViewModel();
        baseInitViewModel();
        mDataBinding.setLifecycleOwner(this);

        init();
        initObserve();
        initListener();
    }

    /**
     * 点击事件-防重复点击
     *
     * @param v
     */
    protected void onMultiClick(View v) {

    }

    public <T extends BaseViewModel> T createViewModel(Class<T> cls) {
        return new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(cls);
    }

    /**
     * 创建ViewModel
     *
     * @param cls        Class
     * @param <T>        Object
     * @param variableId ViewModel的id，如：BR.viewModel
     * @return ViewModel
     */
    public <T extends BaseViewModel> T createViewModel(Class<T> cls, int variableId) {
        this.variableId = variableId;
        return new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(cls);
    }

    /**
     * 初始化状态栏 android 4.4以上沉浸式以及bar的管理
     */
    private void initStatusBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .fitsSystemWindows(false)
                .keyboardEnable(true)
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
                .init();
        setStatusBarLightMode(getWindow(), true);
    }

    /**
     * 设置状态栏高亮模式
     */
    private void setStatusBarLightMode(Window window, boolean isLightMode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = window.getDecorView();
            int vis = decorView.getSystemUiVisibility();
            if (isLightMode) {
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else {
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

    /**
     * 基础的ViewModel初始化
     */
    private void baseInitViewModel() {
        if (null != mViewModel) {
            // 绑定ViewModel
            mDataBinding.setVariable(variableId, mViewModel);
            // ViewModel订阅生命周期事件
            getLifecycle().addObserver(mViewModel);
            // 添加加载状态 observer
            mViewModel.loadState.observe(this, this::addLoadView);
        }
    }

    /**
     * 获取基类的dataBinding对象
     * 用于子类自定义一些特别的试图使用，比如带有网络的activity，通常把显示网络异常的布局(可以时pop)覆盖到业务UI之上，
     * 并且它是一个FrameLayout布局容器
     *
     * @return BaseBinding
     */
    protected GoodsActivityBaseBinding getBaseDataBinding() {
        return mBaseDataBinding;
    }

    /**
     * 初始化业务数据以及view视图
     */
    protected void init() {
    }

    /**
     * 初始化liveData
     */
    protected void initObserve() {
    }

    /**
     * 初始化(view)相关Listener
     */
    protected void initListener() {
    }

    /**
     * 处理Intent
     *
     * @param intent {@link this#getIntent()}
     */
    protected void handleIntent(Intent intent) {
    }

    /**
     * 当前页面的布局资源ID
     *
     * @return @IdRes
     */
    protected abstract int getLayoutResId();

    /**
     * 初始化ViewModel
     */
    protected void initViewModel() {
    }

    /**
     * 添加LoadView到视图
     *
     * @param loadState {@link LoadState}
     */
    private void addLoadView(LoadState loadState) {
        if(!LoadState.LOADING.equals(loadState) && !LoadState.CANCEL_LOADING.equals(loadState)) {
            // 网络加载框不属于UI布局创建
            removeLoadView();
        }
        switch (loadState) {
            case LOADING:
                // 注意：此处一定要替换成布局模式，防止activity跳转或调用activity.start()方式导致实例失效DialogHelper显示不正常
                LoadingDialog loadingDialog = DialogHelper.showProgressDialog(GoodsSdk.getInstance().getTopActivity(), "数据加载中");
                loadingDialog.setCanceledOnTouchOutside(loadState.params.isCancelable);
                loadingDialog.show();
                break;
            case CANCEL_LOADING:
                DialogHelper.dismissProgressDialog();
                break;
            case NO_NETWORK:
                addLoadStateViewForLoadState(mViewNoNetworkBinding, R.layout.goods_view_no_network, loadState);
                break;
            case NO_DATA:
                addLoadStateViewForLoadState(mViewNoDataBinding, R.layout.goods_view_no_data, loadState);
                break;
            case ERROR:
                addLoadStateViewForLoadState(mViewLoadErrorBinding, R.layout.goods_view_load_error, loadState);
                break;
            case DIALOG:
                showDialog(loadState);
                break;
            case FINISH:
                if(null != loadState.params && -1 != loadState.params.setResultCode) {
                    setResult(loadState.params.setResultCode);
                }
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 移除LoadView
     */
    private void removeLoadView() {
        int childCount = mBaseDataBinding.flContentContainer.getChildCount();
        if (childCount > 1) {
            mBaseDataBinding.flContentContainer.removeViews(1, childCount - 1);
        }
    }

    /**
     * 添加LoadState的状态View到业务容器
     *
     * @param obj
     * @param layoutId
     * @param loadState
     */
    private void addLoadStateViewForLoadState(ViewDataBinding obj, int layoutId, LoadState loadState) {
        if (null == loadState.params) {
            return;
        }
        if (null == obj) {
            obj = DataBindingUtil.inflate(getLayoutInflater(), layoutId, mBaseDataBinding.flContentContainer, false);
            obj.setVariable(BR.viewModel, mViewModel);
        }
        // 指定原view视图的具体位置来设置覆盖层的属性
        if (loadState.params.left > 0 || loadState.params.top > 0 || loadState.params.right > 0 || loadState.params.bottom > 0) {
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(-1, -1);
            int screenWidth = mBaseDataBinding.flContentContainer.getWidth();
            int screenHeight = mBaseDataBinding.flContentContainer.getHeight();
            lp.leftMargin = loadState.params.left;
            lp.topMargin = loadState.params.top;
            lp.rightMargin = screenWidth - loadState.params.right;
            lp.bottomMargin = screenHeight - loadState.params.bottom;
            lp.width = loadState.params.right - loadState.params.left;
            lp.height = loadState.params.bottom - loadState.params.top;
            obj.getRoot().setLayoutParams(lp);
        }
        mBaseDataBinding.flContentContainer.addView(obj.getRoot());
    }

    protected void onDialogOnClick(View dialogView) {

    }

    /**
     * 公共弹窗
     * fixme:有时间再来优化此处 cyj
     */
    private void showDialog(LoadState loadState) {
        // 当前合同第X页存在印章覆盖\n请重新拖拽！
//        RoundDialog.Builder builder = new TagBuilder(this)
//                .setTag(loadState.params.tag)
//                .title("温馨提示")
//                .content(loadState.params.message)
//                .contentGravity(Gravity.CENTER)
//                .cancelable(false)
//                .confirmCallback(this::onDialogOnClick);
//        if(!StringUtils.isEmpty(loadState.params.message1)) {
//            builder.cancel(loadState.params.message1);
//        } else {
//            builder.singleBtn(true);
//        }
//
//        builder.confirm(!StringUtils.isEmpty(loadState.params.message2) ? loadState.params.message2 : "知道了");
//        builder.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mViewModel != null) {
            getLifecycle().removeObserver(mViewModel);
        }
        removeLoadView();
    }
}
